package org.example.StudentManagementSystem.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import lombok.RequiredArgsConstructor;
import org.example.StudentManagementSystem.entity.Student;
import org.example.StudentManagementSystem.common.Result;
import org.example.StudentManagementSystem.dto.request.StudentDTO;
import org.example.StudentManagementSystem.service.ClassService;
import org.example.StudentManagementSystem.service.StudentService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/student")
@RequiredArgsConstructor
@CrossOrigin(origins = "*")
public class StudentController {
    @Autowired
    private StudentService studentService;

    @Autowired
    private ClassService classService;

    /**
     * 转换实体类为DTO
     */
    private StudentDTO convertToDTO(Student student) {
        StudentDTO studentDTO = new StudentDTO();
        BeanUtils.copyProperties(student, studentDTO);
        if (student.getClassId() != null) {
            studentDTO.setClassName(classService.getById(student.getClassId()).getName());
        }
        return studentDTO;
    }

    /**
     * 获取学生列表
     */
    @Operation(summary = "获取学生列表")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "成功获取学生列表", content = {
                    @Content(mediaType = "application/json", schema = @Schema(implementation = Result.class))
            }),
            @ApiResponse(responseCode = "404", description = "暂无数据", content = @Content)
    })
    @RequestMapping("")
    public Result getStudentList(
            @Parameter(description = "页码", required = false) @RequestParam(defaultValue = "1") int page,
            @Parameter(description = "每页大小", required = false) @RequestParam(defaultValue = "10") int size) {
        Page<Student> studentPage = studentService.page(Page.of(page, size));
        if (studentPage.getTotal() == 0) {
            return Result.error("暂无数据");
        }
        List<Student> studentList = studentPage.getRecords();
        List<StudentDTO> studentDTOList = studentList.stream().map(this::convertToDTO).collect(Collectors.toList());
        Page<StudentDTO> studentDTOPage = new Page<>();
        studentDTOPage.setCurrent(studentPage.getCurrent());
        studentDTOPage.setSize(studentPage.getSize());
        studentDTOPage.setTotal(studentPage.getTotal());
        studentDTOPage.setRecords(studentDTOList);
        return Result.success(studentDTOPage, "获取学生列表成功");
    }

    /**
     * 获取所有学生
     */
    @Operation(summary = "获取所有学生")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "成功获取所有学生", content = {
                    @Content(mediaType = "application/json", schema = @Schema(implementation = Result.class))
            })
    })
    @RequestMapping("/all")
    public Result getAllStudent() {
        return Result.success(studentService.list(), "获取所有学生成功");
    }

    /**
     * 获取单个学生信息
     */
    @Operation(summary = "获取单个学生信息")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "成功获取学生信息", content = {
                    @Content(mediaType = "application/json", schema = @Schema(implementation = Result.class))
            }),
            @ApiResponse(responseCode = "404", description = "该学生不存在", content = @Content)
    })
    @RequestMapping("/{id}")
    public Result getStudentById(@Parameter(description = "学生ID") @PathVariable int id) {
        Student student = studentService.getById(id);
        if (student == null) {
            return Result.error("该学生不存在");
        }
        StudentDTO studentDTO = convertToDTO(student);
        return Result.success(studentDTO, "获取学生信息成功");
    }

    /**
     * 新增学生
     */
    @Operation(summary = "新增学生")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "成功新增学生", content = {
                    @Content(mediaType = "application/json", schema = @Schema(implementation = Result.class))
            }),
            @ApiResponse(responseCode = "400", description = "学生姓名不能为空", content = @Content)
    })
    @PostMapping("")
    public Result addStudent(@RequestBody Student student) {
        if (student.getName() == null) {
            return Result.error("学生姓名不能为空");
        }
        return studentService.save(student) ? Result.success(student, "新增学生成功") : Result.error("新增学生失败");
    }

    /**
     * 修改学生信息
     */
    @Operation(summary = "修改学生信息")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "成功修改学生信息", content = {
                    @Content(mediaType = "application/json", schema = @Schema(implementation = Result.class))
            }),
            @ApiResponse(responseCode = "400", description = "学生姓名不能为空", content = @Content),
            @ApiResponse(responseCode = "404", description = "该学生不存在", content = @Content)
    })
    @PutMapping("/{id}")
    public Result updateStudent(@Parameter(description = "学生ID") @PathVariable int id, @RequestBody Student student) {
        if (student.getName() == null) {
            return Result.error("学生姓名不能为空");
        }
        student.setId(id);
        return studentService.updateById(student) ? Result.success(student, "修改学生信息成功") : Result.error("修改学生信息失败");
    }

    /**
     * 删除学生
     */
    @Operation(summary = "删除学生")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "成功删除学生", content = {
                    @Content(mediaType = "application/json", schema = @Schema(implementation = Result.class))
            }),
            @ApiResponse(responseCode = "404", description = "该学生不存在", content = @Content)
    })
    @DeleteMapping("/{id}")
    public Result deleteStudent(@Parameter(description = "学生ID") @PathVariable int id) {
        if (studentService.getById(id) == null) {
            return Result.error("该学生不存在");
        }
        return studentService.removeById(id) ? Result.success("删除学生成功") : Result.error("删除学生失败");
    }

    /**
     * 批量删除学生
     */
    @Operation(summary = "批量删除学生")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "成功批量删除学生", content = {
                    @Content(mediaType = "application/json", schema = @Schema(implementation = Result.class))
            }),
            @ApiResponse(responseCode = "400", description = "请选择要删除的学生或该学生不存在", content = @Content)
    })
    @DeleteMapping("")
    public Result deleteStudents(@RequestBody int[] ids) {
        if (ids.length == 0) {
            return Result.error("请选择要删除的学生");
        }
        for (int id : ids) {
            if (studentService.getById(id) == null) {
                return Result.error("该学生不存在");
            }
        }
        List<Integer> idList = Arrays.stream(ids).boxed().collect(Collectors.toList());
        return studentService.removeByIds(idList) ? Result.success("批量删除学生成功") : Result.error("批量删除学生失败");
    }

}
